<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="账单名称" prop="name">
            <el-input v-model="pd.queryParams.name" placeholder="请输入账单名称" clearable style="width: 150px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="单据状态" prop="status">
            <DictSelect dictType="fms_bill_status" v-model:dictValue="pd.queryParams.status" />
          </el-form-item>
          <el-form-item label="计划时间" style="width: 280px">
            <el-date-picker
              v-model="dateRangePlanTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item label="执行时间" style="width: 280px">
            <el-date-picker
              v-model="dateRangeExecutionTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['fms:bill:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()" v-hasPermi="['fms:bill:edit']">修改 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()" v-hasPermi="['fms:bill:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['fms:bill:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.billList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width" width="160">
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Coin"
              @click="handleDivided(scope.row)"
              v-hasPermi="['fms:bill:edit']"
              v-if="scope.row.status === '1'"
            >分期
            </el-button>
            <el-button
              link
              type="primary"
              icon="Finished"
              @click="handleExecBill(scope.row)"
              v-hasPermi="['fms:bill:edit']"
              v-if="scope.row.status === '1'"
            >执行
            </el-button>
            <el-button
              link
              type="primary"
              icon="CloseBold"
              @click="handleBackBill(scope.row)"
              v-hasPermi="['fms:bill:edit']"
              v-if="scope.row.status === '0'"
            >冲销
            </el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['fms:bill:edit']" v-if="scope.row.status === '1'"
            >修改
            </el-button>
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['fms:bill:remove']"
              v-if="scope.row.status === '1'"
            >删除
            </el-button>
          </template>
        </el-table-column>
        <!--        <el-table-column label="主键" align="center" prop="id" v-if="true"/>-->
        <el-table-column label="单据类型" align="center" prop="typeName" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="fms_bill_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column :label="pd.pageParams.costMoney" align="center" prop="costMoney" />
        <el-table-column label="实际金额" align="center" prop="money" />
        <el-table-column label="账单名称" align="center" prop="name" />
        <el-table-column label="来源单号" align="center" prop="sourceId" />
        <el-table-column label="计划时间" align="center" prop="planTime" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.planTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="执行时间" align="center" prop="executionTime" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.executionTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="记账项目" align="center" prop="classificationItemName" />
        <el-table-column label="操作员" align="center" prop="operName" />
        <el-table-column label="账户" align="center" prop="accountName" />
        <el-table-column label="备注" align="center" prop="remark" />
      </el-table>

      <pagination
        v-show="pd.total>0"
        :total="pd.total"
        v-model:page="pd.queryParams.pageNum"
        v-model:limit="pd.queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改财务单据对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="900px" append-to-body>
      <el-form ref="billFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="记账项目" prop="classificationItemId">
              <el-select v-model="pd.form.classificationItemId" placeholder="请选择记账项目">
                <el-option v-for="item in pd.classificationItemList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="pd.pageParams.costMoney" prop="costMoney">
              <el-input v-model="pd.form.costMoney" placeholder="请输入应收金额" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账单名称" prop="name">
              <el-input v-model="pd.form.name" placeholder="请输入账单名称" />
            </el-form-item>
            <el-form-item label="账户" prop="accountId">
              <el-input v-model="pd.form.accountId" placeholder="请输入账户" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划时间" prop="planTime">
              <el-date-picker
                clearable
                v-model="pd.form.planTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择计划时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="pd.form.status" placeholder="请选择状态">
                <el-option v-for="dict in fms_bill_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 财务单据分期对话框 -->
    <el-dialog :title="pd.divideDialog.title" v-model="pd.divideDialog.visible" width="900px" append-to-body>
      <el-form ref="billFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item :label="pd.pageParams.partnerName" prop="partnerName">
              <el-input disabled v-model="pd.form.partnerName" placeholder="请输名称" />
            </el-form-item>
            <el-form-item :label="pd.pageParams.costMoney" prop="costMoney">
              <el-input disabled v-model="pd.form.costMoney" placeholder="请输入金额" />
            </el-form-item>
            <el-form-item label="分期期数">
              <el-input type="" v-model="pd.form.params.periods" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账单名称" prop="name">
              <el-input disabled v-model="pd.form.name" placeholder="请输入账单名称" />
            </el-form-item>
            <el-form-item label="账户" prop="accountId">
              <el-input disabled v-model="pd.form.accountName" placeholder="请输入账户" />
            </el-form-item>
            <el-form-item label="计划时间" prop="planTime">
              <el-date-picker
                clearable
                v-model="pd.form.planTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择计划时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="记账项目" prop="classificationItemId">
              <el-select v-model="pd.form.classificationItemId" placeholder="请选择记账项目">
                <el-option v-for="item in pd.classificationItemList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="操作员" prop="operId">
              <el-input disabled v-model="pd.form.operId" placeholder="请输入操作员" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDivideForm">确 定</el-button>
          <el-button @click="pd.divideDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Bill" lang="ts">
import {addBill, backBill, BillVO, delBill, execBill, listBill, updateBill, divideBill} from '@/views/fms/bill/api';
import DictSelect from '@/views/system/dict/select.vue';
import useUserStore from '@/store/modules/user';
import {listClassificationItem} from "@/api/fms/classificationItem";
import {ClassificationItemVO} from "@/api/fms/classificationItem/types";

const userStore = useUserStore();


const route = useRoute();

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {fms_bill_status} = toRefs<any>(proxy?.useDict('fms_bill_status'));

const dateRangePlanTime = ref<[DateModelType, DateModelType]>(['', '']);
const dateRangeExecutionTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const billFormRef = ref<ElFormInstance>();

const initFormData: BillVO = {
  id: undefined,
  typeId: undefined,
  name: undefined,
  classificationItemId: undefined,
  partnerId: undefined,
  sourceId: undefined,
  operId: undefined,
  costMoney: undefined,
  money: undefined,
  accountId: undefined,
  planTime: undefined,
  executionTime: undefined,
  status: undefined,
  remark: undefined,
}
const pd = reactive({
  billList: <BillVO[]>([]),
  classificationItemList: <ClassificationItemVO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  selectVO: <BillVO[]>([]),
  single: true,
  multiple: true,
  total: 0,
  form: <BillVO>{...initFormData},
  pageParams: {
    typeName: '',
    orderSearchParams: {fmsType:''},
    partnerName: '',
    costMoney: '',
  },
  queryParams: <BillVO>{
    pageNum: 1,
    pageSize: 10,
    typeId: undefined,
    name: undefined,
    partnerId: undefined,
    params: {
      planTime: undefined,
      executionTime: undefined,
    }
  },
  rules: <ElFormRules>{
    id: [{required: true, message: "主键不能为空", trigger: "blur"}],
    typeId: [{required: true, message: "单据类型不能为空", trigger: "blur"}],
    name: [{required: true, message: "账单名称不能为空", trigger: "blur"}],
    classificationItemId: [{required: true, message: "记账项目不能为空", trigger: "blur"}],
    partnerId: [{required: true, message: "客户不能为空", trigger: "blur"}],
    costMoney: [{required: true, message: "应收金额不能为空", trigger: "blur"}],
    accountId: [{required: true, message: "账户不能为空", trigger: "blur"}],
    planTime: [{required: true, message: "计划时间不能为空", trigger: "blur"}],
    status: [{required: true, message: "状态不能为空", trigger: "change"}]
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  },
  divideDialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

/** 分期提交按钮 */
const submitDivideForm = () => {
  divideBill(pd.form).then(res =>{
    handleQuery();
  });
  pd.divideDialog.visible = false;
}

async function handleDivided(row?: BillVO) {
  reset();
  const data = row || pd.selectVO[0]
  Object.assign(pd.form, data);
  pd.form.params = {};
  pd.form.params.periods = 18;
  pd.divideDialog.visible = true;
  pd.divideDialog.title = "财务单据分期";
}

async function handleExecBill(row: BillVO) {
  await proxy?.$modal.confirm('确认要执行吗?');
  await execBill(row).then(res => {
    proxy?.$modal.msgSuccess("执行成功");
    handleQuery();
  });
}


async function handleBackBill(row: BillVO) {
  await proxy?.$modal.confirm('确认要冲销吗?');
  await backBill(row).then(res => {
    proxy?.$modal.msgSuccess("冲销成功");
    handleQuery();
  });
}

/** 查询财务单据列表 */
async function getList() {
  pd.loading = true;
  pd.queryParams.params = {};
  proxy?.addDateRange(pd.queryParams, dateRangePlanTime.value, 'PlanTime');
  proxy?.addDateRange(pd.queryParams, dateRangeExecutionTime.value, 'ExecutionTime');
  if (pd.queryParams.typeId === undefined){
    pd.loading = false;
    proxy?.$modal.msgError("typeId参数不能为空");
  }
  const res = await listBill(pd.queryParams);
  pd.billList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form = {...initFormData};
  billFormRef.value?.resetFields();
  pd.form.typeId = pd.queryParams.typeId;
  pd.form.status = '1';
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRangePlanTime.value = ['', ''];
  dateRangeExecutionTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: BillVO[]) {
  pd.selectVO = selection;
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.dialog.visible = true;
  pd.dialog.title = "添加财务单据";
}

/** 修改按钮操作 */
async function handleUpdate(row?: BillVO) {
  reset();
  const data = row || pd.selectVO[0]
  Object.assign(pd.form, data);
  pd.dialog.visible = true;
  pd.dialog.title = "修改财务单据";
}

/** 提交按钮 */
function submitForm() {
  billFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateBill(pd.form).finally(() => pd.buttonLoading = false);
      } else {
        await addBill(pd.form).finally(() => pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
async function handleDelete(row?: BillVO) {
  const _ids = row?.id || pd.selectVO.map(v => v.id);
  await proxy?.$modal.confirm('是否确认删除财务单据编号为"' + _ids + '"的数据项？').finally(() => pd.loading = false);
  await delBill(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('fms/bill/export', {
    ...pd.queryParams
  }, `bill_${new Date().getTime()}.xlsx`)
}

onMounted(async () => {
  const res = await listClassificationItem();
  pd.classificationItemList = res.rows;

  pd.queryParams.typeId = parseInt(<string>route.query.typeId);
  pd.form.typeId = pd.queryParams.typeId;
  if (pd.queryParams.typeId === 3){
    pd.pageParams.typeName = '内部收款单';
    pd.pageParams.orderSearchParams = {fmsType:'in'};
    pd.pageParams.partnerName = '客户';
    // pd.pageParams.partnerSearchParams = {isCustomer:true};
    pd.pageParams.costMoney = '应收金额';
  } else if (pd.queryParams.typeId === 4){
    pd.pageParams.typeName = '内部付款单';
    pd.pageParams.orderSearchParams = {fmsType:'out'};
    pd.pageParams.partnerName = '供应商';
    // pd.pageParams.partnerSearchParams = {isSupplier:true};
    pd.pageParams.costMoney = '应付金额';
  }
  await getList();
});
</script>
